<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Cesium批量标绘系统（带SVG广告牌）</title>
    <script src="https://cesium.com/downloads/cesiumjs/releases/1.95/Build/Cesium/Cesium.js"></script>
    <link href="https://cesium.com/downloads/cesiumjs/releases/1.95/Build/Cesium/Widgets/widgets.css" rel="stylesheet">
    <style>
        html, body, #cesiumContainer {
            width: 100%; height: 100%; margin: 0; padding: 0; overflow: hidden;
            font-family: 'Microsoft YaHei', Arial, sans-serif;
        }

        #toolbar {
            position: absolute;
            top: 10px;
            left: 10px;
            background: rgba(42, 42, 42, 0.95);
            padding: 15px;
            border-radius: 10px;
            z-index: 1000;
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.5);
            color: #edffff;
            min-width: 280px;
            backdrop-filter: blur(5px);
        }

        .toolbar-section {
            margin-bottom: 15px;
            padding-bottom: 12px;
            border-bottom: 1px solid #4e4e4e;
        }

        .toolbar-section:last-child {
            border-bottom: none;
            margin-bottom: 0;
        }

        .section-title {
            font-weight: bold;
            margin-bottom: 10px;
            color: #48b;
            font-size: 14px;
            display: flex;
            align-items: center;
        }

        .section-title i {
            margin-right: 8px;
            font-size: 16px;
        }

        button {
            background: linear-gradient(to bottom, #4a8, #3a7);
            border: none;
            color: white;
            padding: 8px 12px;
            margin: 5px 3px;
            border-radius: 5px;
            cursor: pointer;
            font-size: 13px;
            transition: all 0.3s;
            box-shadow: 0 2px 5px rgba(0,0,0,0.2);
        }

        button:hover {
            background: linear-gradient(to bottom, #5b9, #4a8);
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0,0,0,0.3);
        }

        button.active {
            background: linear-gradient(to bottom, #e74c3c, #c0392b);
            box-shadow: 0 0 8px rgba(231, 76, 60, 0.7);
        }

        button.clear {
            background: linear-gradient(to bottom, #e74c3c, #c0392b);
        }

        button.clear:hover {
            background: linear-gradient(to bottom, #c0392b, #a93226);
        }

        .color-picker {
            display: inline-block;
            width: 24px;
            height: 24px;
            border-radius: 4px;
            margin: 0 5px 5px 0;
            cursor: pointer;
            border: 2px solid transparent;
            transition: transform 0.2s;
        }

        .color-picker:hover {
            transform: scale(1.1);
        }

        .color-picker.active {
            border: 2px solid white;
            transform: scale(1.1);
        }

        .info-panel {
            position: absolute;
            bottom: 20px;
            left: 20px;
            background: rgba(42, 42, 42, 0.9);
            padding: 12px 18px;
            border-radius: 10px;
            color: #edffff;
            font-size: 14px;
            z-index: 1000;
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.5);
            backdrop-filter: blur(5px);
        }

        .legend {
            position: absolute;
            top: 10px;
            right: 10px;
            background: rgba(42, 42, 42, 0.9);
            padding: 12px 18px;
            border-radius: 10px;
            color: #edffff;
            font-size: 12px;
            z-index: 1000;
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.5);
            backdrop-filter: blur(5px);
            max-width: 200px;
        }

        .legend-item {
            display: flex;
            align-items: center;
            margin: 6px 0;
        }

        .legend-color {
            width: 16px;
            height: 16px;
            margin-right: 10px;
            border-radius: 3px;
        }

        .controls {
            display: flex;
            flex-wrap: wrap;
            gap: 5px;
        }

        .svg-selector {
            margin-top: 10px;
        }

        .svg-option {
            display: inline-block;
            width: 40px;
            height: 40px;
            margin: 0 5px 5px 0;
            cursor: pointer;
            border: 2px solid transparent;
            border-radius: 5px;
            padding: 3px;
            transition: all 0.2s;
        }

        .svg-option:hover {
            border-color: #48b;
        }

        .svg-option.active {
            border-color: #4a8;
            background: rgba(74, 136, 136, 0.2);
        }

        .svg-option svg {
            width: 100%;
            height: 100%;
        }

        .toggle-container {
            display: flex;
            align-items: center;
            margin-top: 8px;
        }

        .toggle-label {
            margin-right: 10px;
            font-size: 13px;
        }

        .toggle-switch {
            position: relative;
            display: inline-block;
            width: 50px;
            height: 24px;
        }

        .toggle-switch input {
            opacity: 0;
            width: 0;
            height: 0;
        }

        .slider {
            position: absolute;
            cursor: pointer;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: #555;
            transition: .4s;
            border-radius: 24px;
        }

        .slider:before {
            position: absolute;
            content: "";
            height: 16px;
            width: 16px;
            left: 4px;
            bottom: 4px;
            background-color: white;
            transition: .4s;
            border-radius: 50%;
        }

        input:checked + .slider {
            background-color: #4a8;
        }

        input:checked + .slider:before {
            transform: translateX(26px);
        }
    </style>
</head>
<body>
<div id="cesiumContainer"></div>

<div id="toolbar">
    <div class="toolbar-section">
        <div class="section-title">
            <i>📍</i> 标绘类型
        </div>
        <div class="controls">
            <button id="pointBtn">点</button>
            <button id="polylineBtn">线</button>
            <button id="polygonBtn">面</button>
            <button id="circleBtn">圆</button>
            <button id="rectangleBtn">矩形</button>
            <button id="billboardBtn">广告牌</button>
        </div>
    </div>

    <div class="toolbar-section">
        <div class="section-title">
            <i>🎨</i> 颜色设置
        </div>
        <div>
            <div class="color-picker" style="background:#ff0000;" data-color="#ff0000"></div>
            <div class="color-picker" style="background:#00ff00;" data-color="#00ff00"></div>
            <div class="color-picker" style="background:#0000ff;" data-color="#0000ff"></div>
            <div class="color-picker" style="background:#ffff00;" data-color="#ffff00"></div>
            <div class="color-picker" style="background:#ff00ff;" data-color="#ff00ff"></div>
            <div class="color-picker" style="background:#00ffff;" data-color="#00ffff"></div>
            <div class="color-picker" style="background:#ffa500;" data-color="#ffa500"></div>
            <div class="color-picker" style="background:#8a2be2;" data-color="#8a2be2"></div>
        </div>
    </div>

    <div class="toolbar-section">
        <div class="section-title">
            <i>🔄</i> 批量操作
        </div>
        <div class="controls">
            <button id="batchAddBtn">批量添加</button>
            <button id="clearAllBtn" class="clear">清除所有</button>
        </div>
    </div>

    <div class="toolbar-section">
        <div class="section-title">
            <i>👁️</i> 显示控制
        </div>
        <div class="controls">
            <button id="toggleAllBtn">显示/隐藏所有</button>
            <button id="flyToBtn">飞行到标绘</button>
        </div>
        <div class="toggle-container">
            <span class="toggle-label">显示广告牌:</span>
            <label class="toggle-switch">
                <input type="checkbox" id="toggleBillboards" checked>
                <span class="slider"></span>
            </label>
        </div>
    </div>

    <div class="toolbar-section svg-selector">
        <div class="section-title">
            <i>🖼️</i> SVG图标
        </div>
        <div>
            <div class="svg-option active" data-svg="pin">
                <svg viewBox="0 0 24 24" fill="#ff0000">
                    <path d="M12 2C8.13 2 5 5.13 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.87-3.13-7-7-7zm0 9.5c-1.38 0-2.5-1.12-2.5-2.5s1.12-2.5 2.5-2.5 2.5 1.12 2.5 2.5-1.12 2.5-2.5 2.5z"/>
                </svg>
            </div>
            <div class="svg-option" data-svg="flag">
                <svg viewBox="0 0 24 24" fill="#00ff00">
                    <path d="M14.4 6L14 4H5v17h2v-7h5.6l.4 2h7V6z"/>
                </svg>
            </div>
            <div class="svg-option" data-svg="star">
                <svg viewBox="0 0 24 24" fill="#ffff00">
                    <path d="M12 17.27L18.18 21l-1.64-7.03L22 9.24l-7.19-.61L12 2 9.19 8.63 2 9.24l5.46 4.73L5.82 21z"/>
                </svg>
            </div>
            <div class="svg-option" data-svg="home">
                <svg viewBox="0 0 24 24" fill="#0000ff">
                    <path d="M10 20v-6h4v6h5v-8h3L12 3 2 12h3v8z"/>
                </svg>
            </div>
            <div class="svg-option" data-svg="alert">
                <svg viewBox="0 0 24 24" fill="#ffa500">
                    <path d="M1 21h22L12 2 1 21zm12-3h-2v-2h2v2zm0-4h-2v-4h2v4z"/>
                </svg>
            </div>
        </div>
    </div>
</div>

<div class="info-panel">
    <div>当前标绘数量: <span id="primitiveCount">0</span></div>
    <div>广告牌数量: <span id="billboardCount">0</span></div>
</div>

<div class="legend">
    <div class="section-title">
        <i>📊</i> 图例
    </div>
    <div class="legend-item">
        <div class="legend-color" style="background:#ff0000;"></div>
        <span>点标绘</span>
    </div>
    <div class="legend-item">
        <div class="legend-color" style="background:#00ff00;"></div>
        <span>线标绘</span>
    </div>
    <div class="legend-item">
        <div class="legend-color" style="background:#0000ff;"></div>
        <span>面标绘</span>
    </div>
    <div class="legend-item">
        <div class="legend-color" style="background:#ffff00;"></div>
        <span>圆标绘</span>
    </div>
    <div class="legend-item">
        <div class="legend-color" style="background:#ff00ff;"></div>
        <span>矩形标绘</span>
    </div>
    <div class="legend-item">
        <div class="legend-color" style="background:#ffa500;"></div>
        <span>广告牌</span>
    </div>
</div>

<script>
    // Cesium Ion访问令牌
    Cesium.Ion.defaultAccessToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiIwNWY1NDhkNy00NDI4LTQyZWQtYTRmNS1iNGQ0MjMxNDIzZWMiLCJpZCI6MTU0NDA1LCJpYXQiOjE2ODk1NzY0ODl9.1zt09SfJKVhZNs-zzn3fN5pzpkrYEzatuDTZYviZx1I";

    // 初始化Cesium Viewer
    const viewer = new Cesium.Viewer('cesiumContainer', {
        terrainProvider: Cesium.createWorldTerrain(),
        timeline: false,
        animation: false,
        sceneModePicker: false,
        baseLayerPicker: false,
        geocoder: false,
        homeButton: false,
        fullscreenButton: false,
        vrButton: false,
        navigationHelpButton: false,
        selectionIndicator: false,
        infoBox: false
    });

    // 设置初始视角
    viewer.camera.setView({
        destination: Cesium.Cartesian3.fromDegrees(116.39, 39.91, 10000000),
        orientation: {
            heading: 0,
            pitch: -1.57,
            roll: 0
        }
    });

    // 全局变量
    let primitives = [];
    let billboards = [];
    let currentColor = Cesium.Color.RED;
    let currentPrimitiveType = 'point';
    let currentSvgType = 'pin';
    let isDrawing = false;
    let tempPrimitive = null;
    let drawingPositions = [];
    let drawingHandler = null;

    // SVG图标定义
    const svgIcons = {
        pin: `<svg viewBox="0 0 24 24" fill="{color}"><path d="M12 2C8.13 2 5 5.13 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.87-3.13-7-7-7zm0 9.5c-1.38 0-2.5-1.12-2.5-2.5s1.12-2.5 2.5-2.5 2.5 1.12 2.5 2.5-1.12 2.5-2.5 2.5z"/></svg>`,
        flag: `<svg viewBox="0 0 24 24" fill="{color}"><path d="M14.4 6L14 4H5v17h2v-7h5.6l.4 2h7V6z"/></svg>`,
        star: `<svg viewBox="0 0 24 24" fill="{color}"><path d="M12 17.27L18.18 21l-1.64-7.03L22 9.24l-7.19-.61L12 2 9.19 8.63 2 9.24l5.46 4.73L5.82 21z"/></svg>`,
        home: `<svg viewBox="0 0 24 24" fill="{color}"><path d="M10 20v-6h4v6h5v-8h3L12 3 2 12h3v8z"/></svg>`,
        alert: `<svg viewBox="0 0 24 24" fill="{color}"><path d="M1 21h22L12 2 1 21zm12-3h-2v-2h2v2zm0-4h-2v-4h2v4z"/></svg>`
    };

    // 初始化UI事件
    document.getElementById('pointBtn').addEventListener('click', () => setPrimitiveType('point'));
    document.getElementById('polylineBtn').addEventListener('click', () => setPrimitiveType('polyline'));
    document.getElementById('polygonBtn').addEventListener('click', () => setPrimitiveType('polygon'));
    document.getElementById('circleBtn').addEventListener('click', () => setPrimitiveType('circle'));
    document.getElementById('rectangleBtn').addEventListener('click', () => setPrimitiveType('rectangle'));
    document.getElementById('billboardBtn').addEventListener('click', () => setPrimitiveType('billboard'));

    document.getElementById('batchAddBtn').addEventListener('click', batchAddPrimitives);
    document.getElementById('clearAllBtn').addEventListener('click', clearAllPrimitives);
    document.getElementById('toggleAllBtn').addEventListener('click', toggleAllPrimitives);
    document.getElementById('flyToBtn').addEventListener('click', flyToPrimitives);

    // 颜色选择器
    const colorPickers = document.querySelectorAll('.color-picker');
    colorPickers.forEach(picker => {
        picker.addEventListener('click', function() {
            colorPickers.forEach(p => p.classList.remove('active'));
            this.classList.add('active');
            currentColor = Cesium.Color.fromCssColorString(this.getAttribute('data-color'));
        });
    });

    // SVG选择器
    const svgOptions = document.querySelectorAll('.svg-option');
    svgOptions.forEach(option => {
        option.addEventListener('click', function() {
            svgOptions.forEach(o => o.classList.remove('active'));
            this.classList.add('active');
            currentSvgType = this.getAttribute('data-svg');
        });
    });

    // 广告牌显示切换
    document.getElementById('toggleBillboards').addEventListener('change', function() {
        const show = this.checked;
        billboards.forEach(billboard => {
            billboard.show = show;
        });
    });

    // 设置默认颜色
    colorPickers[0].classList.add('active');

    // 设置标绘类型
    function setPrimitiveType(type) {
        // 重置按钮状态
        document.querySelectorAll('#toolbar button').forEach(btn => {
            if (btn.id.endsWith('Btn') && btn.id !== 'batchAddBtn' && btn.id !== 'clearAllBtn' &&
                btn.id !== 'toggleAllBtn' && btn.id !== 'flyToBtn') {
                btn.classList.remove('active');
            }
        });

        // 设置当前类型
        currentPrimitiveType = type;
        document.getElementById(type + 'Btn').classList.add('active');

        // 清除之前的绘图状态
        if (isDrawing) {
            cancelDrawing();
        }

        // 开始新的绘图
        if (type !== 'billboard') {
            startDrawing();
        } else {
            // 广告牌模式
            viewer.canvas.style.cursor = 'crosshair';
            drawingHandler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
            drawingHandler.setInputAction(onBillboardClick, Cesium.ScreenSpaceEventType.LEFT_CLICK);
        }
    }

    // 开始绘图
    function startDrawing() {
        isDrawing = true;

        // 设置鼠标样式
        viewer.canvas.style.cursor = 'crosshair';

        // 添加鼠标左键点击事件
        drawingHandler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);

        if (currentPrimitiveType === 'point') {
            drawingHandler.setInputAction(onPointClick, Cesium.ScreenSpaceEventType.LEFT_CLICK);
        } else if (currentPrimitiveType === 'polyline') {
            drawingHandler.setInputAction(onPolylineClick, Cesium.ScreenSpaceEventType.LEFT_CLICK);
            drawingHandler.setInputAction(onRightClick, Cesium.ScreenSpaceEventType.RIGHT_CLICK);
        } else if (currentPrimitiveType === 'polygon') {
            drawingHandler.setInputAction(onPolygonClick, Cesium.ScreenSpaceEventType.LEFT_CLICK);
            drawingHandler.setInputAction(onRightClick, Cesium.ScreenSpaceEventType.RIGHT_CLICK);
        } else if (currentPrimitiveType === 'circle') {
            drawingHandler.setInputAction(onCircleClick, Cesium.ScreenSpaceEventType.LEFT_CLICK);
        } else if (currentPrimitiveType === 'rectangle') {
            drawingHandler.setInputAction(onRectangleClick, Cesium.ScreenSpaceEventType.LEFT_CLICK);
        }
    }

    // 取消绘图
    function cancelDrawing() {
        if (drawingHandler) {
            drawingHandler.destroy();
            drawingHandler = null;
        }

        if (tempPrimitive) {
            viewer.scene.primitives.remove(tempPrimitive);
            tempPrimitive = null;
        }

        drawingPositions = [];
        isDrawing = false;
        viewer.canvas.style.cursor = 'default';
    }

    // 点标绘点击事件
    function onPointClick(event) {
        const position = viewer.camera.pickEllipsoid(event.position, viewer.scene.globe.ellipsoid);
        if (position) {
            addPointPrimitive(position);
        }
    }

    // 折线标绘点击事件
    function onPolylineClick(event) {
        const position = viewer.camera.pickEllipsoid(event.position, viewer.scene.globe.ellipsoid);
        if (position) {
            drawingPositions.push(position);

            if (drawingPositions.length === 1) {
                // 第一个点，创建临时折线
                tempPrimitive = viewer.scene.primitives.add(new Cesium.PolylineCollection());
                const polyline = tempPrimitive.add({
                    positions: drawingPositions,
                    width: 3,
                    material: Cesium.Material.fromType('Color', {
                        color: currentColor.withAlpha(0.7)
                    })
                });
            } else {
                // 更新临时折线
                tempPrimitive.get(0).positions = drawingPositions;
            }
        }
    }

    // 多边形标绘点击事件
    function onPolygonClick(event) {
        const position = viewer.camera.pickEllipsoid(event.position, viewer.scene.globe.ellipsoid);
        if (position) {
            drawingPositions.push(position);

            if (drawingPositions.length === 1) {
                // 第一个点，创建临时多边形
                tempPrimitive = viewer.scene.primitives.add(new Cesium.Primitive({
                    geometryInstances: new Cesium.GeometryInstance({
                        geometry: new Cesium.PolygonGeometry({
                            polygonHierarchy: new Cesium.PolygonHierarchy(drawingPositions),
                            height: 0
                        })
                    }),
                    appearance: new Cesium.PerInstanceColorAppearance({
                        flat: true,
                        translucent: true
                    })
                }));

                // 设置颜色
                const colorAttribute = Cesium.ColorGeometryInstanceAttribute.fromColor(
                    currentColor.withAlpha(0.5)
                );
                tempPrimitive.getGeometryInstanceAttributes().color = colorAttribute;
            } else {
                // 更新临时多边形
                const geometry = new Cesium.PolygonGeometry({
                    polygonHierarchy: new Cesium.PolygonHierarchy(drawingPositions),
                    height: 0
                });
                tempPrimitive.geometryInstances.geometry = geometry;
            }
        }
    }

    // 圆形标绘点击事件
    function onCircleClick(event) {
        const position = viewer.camera.pickEllipsoid(event.position, viewer.scene.globe.ellipsoid);
        if (position) {
            addCirclePrimitive(position, 100000); // 100km半径
            cancelDrawing();
        }
    }

    // 矩形标绘点击事件
    function onRectangleClick(event) {
        const position = viewer.camera.pickEllipsoid(event.position, viewer.scene.globe.ellipsoid);
        if (position) {
            const cartographic = Cesium.Cartographic.fromCartesian(position);
            const longitude = Cesium.Math.toDegrees(cartographic.longitude);
            const latitude = Cesium.Math.toDegrees(cartographic.latitude);

            // 创建矩形（2度 x 2度）
            const rectangle = Cesium.Rectangle.fromDegrees(
                longitude - 1, latitude - 1,
                longitude + 1, latitude + 1
            );

            addRectanglePrimitive(rectangle);
            cancelDrawing();
        }
    }

    // 广告牌点击事件
    function onBillboardClick(event) {
        const position = viewer.camera.pickEllipsoid(event.position, viewer.scene.globe.ellipsoid);
        if (position) {
            addBillboard(position);
            cancelDrawing();
        }
    }

    // 右键点击完成绘制
    function onRightClick(event) {
        if (drawingPositions.length > 1) {
            if (currentPrimitiveType === 'polyline') {
                addPolylinePrimitive(drawingPositions);
            } else if (currentPrimitiveType === 'polygon') {
                addPolygonPrimitive(drawingPositions);
            }
        }
        cancelDrawing();
    }

    // 添加点标绘
    function addPointPrimitive(position) {
        const pointPrimitive = viewer.scene.primitives.add(new Cesium.PointPrimitiveCollection());
        const point = pointPrimitive.add({
            position: position,
            color: currentColor,
            pixelSize: 10,
            outlineColor: Cesium.Color.WHITE,
            outlineWidth: 2
        });

        primitives.push({
            type: 'point',
            primitive: pointPrimitive,
            positions: [position]
        });

        updatePrimitiveCount();
        cancelDrawing();
    }

    // 添加折线标绘
    function addPolylinePrimitive(positions) {
        const polyline = viewer.scene.primitives.add(new Cesium.PolylineCollection());
        polyline.add({
            positions: positions,
            width: 3,
            material: Cesium.Material.fromType('Color', {
                color: currentColor
            })
        });

        primitives.push({
            type: 'polyline',
            primitive: polyline,
            positions: positions
        });

        updatePrimitiveCount();
    }

    // 添加多边形标绘
    function addPolygonPrimitive(positions) {
        const polygon = viewer.scene.primitives.add(new Cesium.Primitive({
            geometryInstances: new Cesium.GeometryInstance({
                geometry: new Cesium.PolygonGeometry({
                    polygonHierarchy: new Cesium.PolygonHierarchy(positions),
                    height: 0
                })
            }),
            appearance: new Cesium.PerInstanceColorAppearance({
                flat: true
            })
        }));

        // 设置颜色
        const colorAttribute = Cesium.ColorGeometryInstanceAttribute.fromColor(
            currentColor.withAlpha(0.7)
        );
        polygon.getGeometryInstanceAttributes().color = colorAttribute;

        primitives.push({
            type: 'polygon',
            primitive: polygon,
            positions: positions
        });

        updatePrimitiveCount();
    }

    // 添加圆形标绘
    function addCirclePrimitive(center, radius) {
        const circle = viewer.scene.primitives.add(new Cesium.Primitive({
            geometryInstances: new Cesium.GeometryInstance({
                geometry: new Cesium.CircleGeometry({
                    center: center,
                    radius: radius,
                    vertexFormat: Cesium.PerInstanceColorAppearance.VERTEX_FORMAT
                })
            }),
            appearance: new Cesium.PerInstanceColorAppearance({
                flat: true,
                translucent: true
            })
        }));

        // 设置颜色
        const colorAttribute = Cesium.ColorGeometryInstanceAttribute.fromColor(
            currentColor.withAlpha(0.5)
        );
        circle.getGeometryInstanceAttributes().color = colorAttribute;

        primitives.push({
            type: 'circle',
            primitive: circle,
            positions: [center],
            radius: radius
        });

        updatePrimitiveCount();
    }

    // 添加矩形标绘
    function addRectanglePrimitive(rectangle) {
        const rect = viewer.scene.primitives.add(new Cesium.Primitive({
            geometryInstances: new Cesium.GeometryInstance({
                geometry: new Cesium.RectangleGeometry({
                    rectangle: rectangle,
                    vertexFormat: Cesium.PerInstanceColorAppearance.VERTEX_FORMAT
                })
            }),
            appearance: new Cesium.PerInstanceColorAppearance({
                flat: true,
                translucent: true
            })
        }));

        // 设置颜色
        const colorAttribute = Cesium.ColorGeometryInstanceAttribute.fromColor(
            currentColor.withAlpha(0.5)
        );
        rect.getGeometryInstanceAttributes().color = colorAttribute;

        primitives.push({
            type: 'rectangle',
            primitive: rect,
            rectangle: rectangle
        });

        updatePrimitiveCount();
    }

    // 添加广告牌
    function addBillboard(position) {
        // 创建SVG数据URL
        const svgString = svgIcons[currentSvgType].replace(/{color}/g, currentColor.toCssColorString());
        const svgBlob = new Blob([svgString], {type: 'image/svg+xml'});
        const svgUrl = URL.createObjectURL(svgBlob);

        const billboard = viewer.entities.add({
            position: position,
            billboard: {
                image: svgUrl,
                width: 40,
                height: 40,
                verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
                scale: 1.0,
                color: currentColor
            }
        });

        billboards.push(billboard);
        updatePrimitiveCount();
    }

    // 批量添加标绘
    function batchAddPrimitives() {
        // 清除现有标绘
        clearAllPrimitives();

        // 生成随机位置
        const centerLongitude = 116.39;
        const centerLatitude = 39.91;
        const spread = 5; // 经纬度扩散范围

        // 批量添加点
        for (let i = 0; i < 8; i++) {
            const longitude = centerLongitude + (Math.random() - 0.5) * spread;
            const latitude = centerLatitude + (Math.random() - 0.5) * spread;
            const position = Cesium.Cartesian3.fromDegrees(longitude, latitude);

            currentColor = Cesium.Color.fromRandom({alpha: 1.0});
            addPointPrimitive(position);
        }

        // 批量添加折线
        for (let i = 0; i < 4; i++) {
            const positions = [];
            for (let j = 0; j < 4; j++) {
                const longitude = centerLongitude + (Math.random() - 0.5) * spread;
                const latitude = centerLatitude + (Math.random() - 0.5) * spread;
                positions.push(Cesium.Cartesian3.fromDegrees(longitude, latitude));
            }

            currentColor = Cesium.Color.fromRandom({alpha: 1.0});
            addPolylinePrimitive(positions);
        }

        // 批量添加多边形
        for (let i = 0; i < 3; i++) {
            const positions = [];
            for (let j = 0; j < 5; j++) {
                const longitude = centerLongitude + (Math.random() - 0.5) * spread;
                const latitude = centerLatitude + (Math.random() - 0.5) * spread;
                positions.push(Cesium.Cartesian3.fromDegrees(longitude, latitude));
            }

            currentColor = Cesium.Color.fromRandom({alpha: 0.7});
            addPolygonPrimitive(positions);
        }

        // 批量添加圆形
        for (let i = 0; i < 3; i++) {
            const longitude = centerLongitude + (Math.random() - 0.5) * spread;
            const latitude = centerLatitude + (Math.random() - 0.5) * spread;
            const position = Cesium.Cartesian3.fromDegrees(longitude, latitude);
            const radius = 50000 + Math.random() * 100000; // 50-150km半径

            currentColor = Cesium.Color.fromRandom({alpha: 0.5});
            addCirclePrimitive(position, radius);
        }

        // 批量添加矩形
        for (let i = 0; i < 2; i++) {
            const longitude = centerLongitude + (Math.random() - 0.5) * spread;
            const latitude = centerLatitude + (Math.random() - 0.5) * spread;

            const rectangle = Cesium.Rectangle.fromDegrees(
                longitude - 0.5, latitude - 0.3,
                longitude + 0.5, latitude + 0.3
            );

            currentColor = Cesium.Color.fromRandom({alpha: 0.5});
            addRectanglePrimitive(rectangle);
        }

        // 批量添加广告牌
        for (let i = 0; i < 6; i++) {
            const longitude = centerLongitude + (Math.random() - 0.5) * spread;
            const latitude = centerLatitude + (Math.random() - 0.5) * spread;
            const position = Cesium.Cartesian3.fromDegrees(longitude, latitude);

            currentColor = Cesium.Color.fromRandom({alpha: 1.0});
            // 随机选择SVG类型
            const svgTypes = Object.keys(svgIcons);
            currentSvgType = svgTypes[Math.floor(Math.random() * svgTypes.length)];
            addBillboard(position);
        }

        // 飞行到标绘区域
        flyToPrimitives();
    }

    // 清除所有标绘
    function clearAllPrimitives() {
        primitives.forEach(item => {
            viewer.scene.primitives.remove(item.primitive);
        });
        primitives = [];

        billboards.forEach(billboard => {
            viewer.entities.remove(billboard);
        });
        billboards = [];

        updatePrimitiveCount();
    }

    // 显示/隐藏所有标绘
    function toggleAllPrimitives() {
        const visible = primitives.length > 0 ? !primitives[0].primitive.show : false;
        primitives.forEach(item => {
            item.primitive.show = visible;
        });

        const billboardVisible = billboards.length > 0 ? !billboards[0].show : false;
        billboards.forEach(billboard => {
            billboard.show = billboardVisible;
        });
    }

    // 飞行到标绘区域
    function flyToPrimitives() {
        if (primitives.length === 0 && billboards.length === 0) return;

        // 计算所有标绘的边界
        let minLon = 180, maxLon = -180, minLat = 90, maxLat = -90;

        primitives.forEach(item => {
            if (item.positions) {
                item.positions.forEach(position => {
                    const cartographic = Cesium.Cartographic.fromCartesian(position);
                    const lon = Cesium.Math.toDegrees(cartographic.longitude);
                    const lat = Cesium.Math.toDegrees(cartographic.latitude);

                    minLon = Math.min(minLon, lon);
                    maxLon = Math.max(maxLon, lon);
                    minLat = Math.min(minLat, lat);
                    maxLat = Math.max(maxLat, lat);
                });
            } else if (item.rectangle) {
                const rect = item.rectangle;
                minLon = Math.min(minLon, Cesium.Math.toDegrees(rect.west));
                maxLon = Math.max(maxLon, Cesium.Math.toDegrees(rect.east));
                minLat = Math.min(minLat, Cesium.Math.toDegrees(rect.south));
                maxLat = Math.max(maxLat, Cesium.Math.toDegrees(rect.north));
            }
        });

        billboards.forEach(billboard => {
            const position = billboard.position.getValue(Cesium.JulianDate.now());
            const cartographic = Cesium.Cartographic.fromCartesian(position);
            const lon = Cesium.Math.toDegrees(cartographic.longitude);
            const lat = Cesium.Math.toDegrees(cartographic.latitude);

            minLon = Math.min(minLon, lon);
            maxLon = Math.max(maxLon, lon);
            minLat = Math.min(minLat, lat);
            maxLat = Math.max(maxLat, lat);
        });

        // 设置飞行目标
        const rectangle = Cesium.Rectangle.fromDegrees(minLon - 1, minLat - 1, maxLon + 1, maxLat + 1);
        viewer.camera.flyTo({
            destination: rectangle
        });
    }

    // 更新标绘数量显示
    function updatePrimitiveCount() {
        document.getElementById('primitiveCount').textContent = primitives.length;
        document.getElementById('billboardCount').textContent = billboards.length;
    }

    // 初始化：默认选择点标绘
    setPrimitiveType('point');
</script>
</body>
</html>